<script setup>
import { Modal } from 'ant-design-vue'
import { ColumnHeightOutlined, DownOutlined, PlusOutlined, ReloadOutlined, SettingOutlined, UpOutlined } from '@ant-design/icons-vue'
import { getChannelName, getWithdrawalList } from '~@/api/order/index'

defineOptions({
  name: 'WITHDRAWAL',
})
// const statusMap = {
//   0: '关闭',
//   1: '运行中',
//   2: '上线',
//   3: '错误',
// }
const message = useMessage()
const columns = shallowRef([

  {
    title: '平台订单号',
    dataIndex: 'withdrawalNo',
    width: 250,
  },
  // {
  //   title: '商户订单号',
  //   dataIndex: 'defrayNo',
  //   width: 250,
  // },

  {
    title: '交易卡号',
    dataIndex: 'cardNo',
    width: 250,
  },
  {
    title: '提现金额',
    align: 'center',
    dataIndex: 'withdrawalFee',
    width: 130,

  },
  {
    title: '提现渠道',
    align: 'center',
    dataIndex: 'channelName',
    width: 130,

  },
  {
    title: '状态',
    dataIndex: 'status',
    align: 'center',
    width: 150,
    customRender: ({ text }) => {
      /**
       * 订单状态
       *
       */
      switch (text) {
        case 'CREATED':
          return '已创建'
        case 'WAITING_PAYMENT':
          return '等待支付'
        case 'WAITING_PAYMENT_RESULT':
          return '等待支付处理结果'
        case 'SUCCESS':
          return '交易成功'
        case 'FAILED':
          return '交易失败'
        case 'TRADE_CLOSED':
          return '交易关闭'
        default:
          return '订单已取消'
      }
    },
  },

  // {
  //   title: '创建时间',
  //   align: 'center',
  //   dataIndex: 'withdrawalStartTime',
  //   width: 160,
  // },
  {
    title: '交易时间',
    align: 'center',
    dataIndex: 'withdrawalCompleteTime',
    width: 200,
  },

  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    fixed: 'right',
    width: 110,

  },
])
const tradeOptions = shallowRef([
  // { label: '支付', value: 'DEFRAY' },
  // { label: '退费', value: 'REFUND' },
  // { label: '充值', value: 'RECHARGE' },
  // { label: '提现', value: 'WITHDRAWAL' },
])
const channelOptions = shallowRef([])
const merchantOptions = shallowRef([])
const statusOptions = shallowRef([
  { configValue: '已创建', configKey: 'CREATED' },
  { configValue: '等待支付', configKey: 'WAITING_PAYMENT' },
  { configValue: '等待支付处理结果', configKey: 'WAITING_PAYMENT_RESULT' },
  { configValue: '交易成功', configKey: 'SUCCESS' },
  { configValue: '交易失败', configKey: 'FAILED' },
  { configValue: '交易关闭', configKey: 'TRADE_CLOSED' },
  { configValue: '交易成功', configKey: 'SUCCESS' },
  { configValue: '订单已取消', configKey: 'CANCELED' },
])
const loading = shallowRef(false)
const merchantloading = shallowRef(false)
const totalNum = shallowRef(0)
const pagination = reactive({
  pageSize: 8,
  pageSizeOptions: ['10', '20', '30', '40'],
  current: 1,
  total: totalNum,
  showSizeChanger: true,
  // showQuickJumper: true,
  showTotal: total => `总共：${total}`,
  onChange(current, pageSize) {
    pagination.pageSize = pageSize
    pagination.current = current
    init()
  },
})
const dataSource = shallowRef([])
const detailInfo = shallowRef({
  appName: void 0,
  platRequestNo: void 0,
  accountNo: void 0,
  appId: void 0,
  cardNo: void 0,
  tradeType: void 0,
  tradeDate: void 0,
  channel: void 0,
  phone: void 0,
  userName: void 0,
  requestCompleteTime: void 0,
  requestStartTime: void 0,
  channelName: void 0,
  defrayFee: void 0,
  status: void 0,
  origPlatRequestNo: void 0,
  defrayNo: void 0,

})
const formModel = reactive({
  withdrawalNo: void 0,
  cardNo: void 0,
  status: void 0,
  tradeDate: void 0,
  channelFilter: void 0,
})
const tableSize = ref(['large'])
const open = ref(false)
const options = computed(() => {
  return columns.value.map((item) => {
    if (item.dataIndex === 'action') {
      return {
        label: item.title,
        value: item.dataIndex,
        disabled: true,
      }
    }
    return {
      label: item.title,
      value: item.dataIndex,
    }
  })
})
const dropdownVisible = ref(false)
const getCheckList = computed(() => columns.value.map(item => item.dataIndex))
const state = reactive({
  indeterminate: false,
  checkAll: true,
  checkList: getCheckList.value,
})
onMounted(() => {
  init()
  getType()
  getChannel()
})
// 查询交易类型字典值
async function getType() {
  try {
    const res = await getTradeType()
    // window.location.href='https://heren-pay-reconciliation.cn-hangzhou.oss.aliyuncs.com/test/card/bill/CARD_RECHARGE20250307.xls'
    tradeOptions.value = res.data
  }
  catch (e) {
  }
  finally {
    console.log(11)
  }
}

// 查询充值提现字典值
async function getChannel() {
  try {
    const res = await getChannelName()
    // window.location.href='https://heren-pay-reconciliation.cn-hangzhou.oss.aliyuncs.com/test/card/bill/CARD_RECHARGE20250307.xls'
    channelOptions.value = res.data
  }
  catch (e) {
  }
  finally {
    console.log(22)
  }
}
async function init() {
  if (loading.value)
    return
  loading.value = true
  try {
    const startDate = formModel.tradeDate?.[0]?.format('YYYY-MM-DD')
    const endDate = formModel.tradeDate?.[1]?.format('YYYY-MM-DD')
    const { data } = await getWithdrawalList({
      param: { ...formModel, startDate, endDate },
      page: {
        currentPage: pagination.current,
        pageSize: pagination.pageSize,
      },

    })

    dataSource.value = data.data ?? []
    totalNum.value = data?.pageInfo.total
    console.log(111, totalNum.value)
  }
  catch (e) {
    console.log(e)
  }
  finally {
    loading.value = false
  }
}
async function onSearch() {
  pagination.current = 1
  await init()
}
// 防抖优化接口请求
async function fetchOptions(value) {
  if (!value.trim()) {
    merchantOptions.value = []
    return
  }
  merchantloading.value = true
  const { data } = await getMerchantList(value)
  merchantOptions.value = data
  merchantloading.value = false
};
async function onReset() {
  formModel.withdrawalNo = void 0
  formModel.cardNo = void 0
  formModel.endDate = void 0
  formModel.startDate = void 0
  formModel.tradeDate = void 0
  formModel.channelFilter = void 0
  formModel.status = void 0
  await init()
}
/**
 * 详情
 *  @param record
 *
 */
async function handleDetail(record) {
  open.value = true
  detailInfo.value = record
}
function handleReturn() {
  open.value = false
}
/**
 * 交易类型
 *
 */
function handleTradeType(type) {
  switch (type) {
    case 'DEFRAY':
      return '支付'
    case 'REFUND':
      return '退费'
    case 'RECHARGE':
      return '充值'
    default:
      return '提现'
  }
}
/**
 * 订单状态
 *
 */
function handleStatus(status) {
  switch (status) {
    case 'CREATED':
      return '已创建'
    case 'WAITING_PAYMENT':
      return '等待支付'
    case 'WAITING_PAYMENT_RESULT':
      return '等待支付处理结果'
    case 'SUCCESS':
      return '交易成功'
    case 'FAILED':
      return '交易失败'
    case 'TRADE_CLOSED':
      return '交易关闭'
    default:
      return '订单已取消'
  }
}
function handleOk() {
  open.value = false
  Modal.destroyAll()
  onSearch()
}
function handleSizeChange(e) {
  tableSize.value[0] = e.key
}
function filterAction(value) {
  return columns.value.filter((item) => {
    if (value.includes(item.dataIndex))
      return true

    return false
  })
}
const filterColumns = ref(filterAction(getCheckList.value))
function handleCheckAllChange(e) {
  Object.assign(state, {
    checkList: e.target.checked ? getCheckList.value : [],
    indeterminate: true,
  })
  filterColumns.value = e.target.checked ? filterAction(getCheckList.value) : filterColumns.value.filter(item => item.dataIndex === 'action')
}
watch(
  () => state.checkList,
  (val) => {
    state.indeterminate = !!val.length && val.length < getCheckList.value.length
    state.checkAll = val.length === getCheckList.value.length
  },
)
function handleResetChange() {
  state.checkList = getCheckList.value
  filterColumns.value = filterAction(getCheckList.value)
}
function handleCheckChange(value) {
  const filterValue = filterAction(value)
  filterColumns.value = filterValue
}

const expand = ref(false)
</script>

<template>
  <page-container>
    <a-card mb-4>
      <a-form :label-col="{ span: 7 }" :model="formModel">
        <a-row :gutter="[15, 0]">
          <a-col :span="8">
            <a-form-item name="withdrawalNo" label="平台订单号">
              <a-input v-model:value="formModel.withdrawalNo" placeholder="精确查询" allow-clear />
            </a-form-item>
          </a-col>
          <!-- <a-col :span="8">
              <a-form-item name="rechargeNo" label="商户订单号">
                <a-input v-model:value="formModel.rechargeNo" placeholder="精确查询" allow-clear />
              </a-form-item>
            </a-col> -->
          <a-col :span="8">
            <a-form-item name="tradeDate" label="交易时间">
              <a-range-picker v-model:value="formModel.tradeDate" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item name="cardNo" label="交易卡号">
              <a-input v-model:value="formModel.cardNo" placeholder="精确查询" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item name="appId" label="提现渠道">
              <a-select v-model:value="formModel.channelFilter" placeholder="请选择" allow-clear>
                <a-select-option v-for="item in channelOptions" :key="item.configKey" :value="item.configKey">
                  {{ item.configValue }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item name="appId" label="订单状态">
              <a-select v-model:value="formModel.status" placeholder="请选择" allow-clear>
                <a-select-option v-for="item in statusOptions" :key="item.configKey" :value="item.configKey">
                  {{ item.configValue }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row v-if="expand" :gutter="[15, 0]">
          <a-col :span="8">
            <a-form-item name="channel" label="充值提现渠道">
              <a-select v-model:value="formModel.channel" placeholder="请选择" allow-clear>
                <a-select-option v-for="item in channelOptions" :key="item.configKey" :value="item.configKey">
                  {{ item.configValue }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :span="24" style="text-align: right">
          <a-col :span="24">
            <a-space flex justify-end w-full>
              <!-- :loading="loading" -->
              <a-button type="primary" @click="onSearch">
                查询
              </a-button>
              <a-button @click="onReset">
                重置
              </a-button>
              <!-- <a-button type="link" @click="expand = !expand">
                    {{ expand ? '收起' : '高级筛选' }}
                    <UpOutlined v-if="expand" />
                    <DownOutlined v-else />
                  </a-button> -->
            </a-space>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <a-card>
      <a-table bordered :loading="loading" :columns="filterColumns" :scroll="{ x: 1000 }" :data-source="dataSource" :pagination="pagination">
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'withdrawalFee'">
            <span :style="{ color: record.withdrawalFee < 0 ? 'red' : 'black' }">{{ Number(record.withdrawalFee).toFixed(2) }}</span>
          </template>

          <template v-else-if="column.dataIndex === 'action'">
            <a @click="handleDetail(record)">详情</a>
          </template>
        </template>
      </a-table>
    </a-card>
    <a-modal v-model:open="open" title="查看详情" width="900px" :mask-closable="false" :footer="null" @ok="handleOk">
      <a-card class="transition-all-300" :bordered="false">
        <a-descriptions :column="2">
          <a-descriptions-item label="平台订单号">
            {{ detailInfo.withdrawalNo }}
          </a-descriptions-item>
          <a-descriptions-item label="HIS流水号">
            {{ detailInfo.appTradeNo ? detailInfo.appTradeNo : "--" }}
          </a-descriptions-item>
          <a-descriptions-item label="第三方流水号">
            {{ detailInfo.channelTradeNo ? detailInfo.channelTradeNo : "--" }}
          </a-descriptions-item>
          <a-descriptions-item label="商户订单号">
            {{ detailInfo.defrayNo ? detailInfo.defrayNo : "--" }}
          </a-descriptions-item>
          <a-descriptions-item label="交易卡号">
            {{ detailInfo.cardNo }}
          </a-descriptions-item>
          <a-descriptions-item label="账号">
            {{ detailInfo.accountNo ? detailInfo.accountNo : "--" }}
          </a-descriptions-item>
          <a-descriptions-item label="提现金额">
            {{ detailInfo.withdrawalFee ? Number(detailInfo.withdrawalFee).toFixed(2) : '--' }}
          </a-descriptions-item>
          <a-descriptions-item label="提现渠道">
            {{ detailInfo.channelName }}
          </a-descriptions-item>
          <a-descriptions-item label="提现开始时间">
            {{ detailInfo.withdrawalStartTime ? detailInfo.withdrawalStartTime : '--' }}
          </a-descriptions-item>
          <a-descriptions-item label="提现完成时间">
            {{ detailInfo.withdrawalCompleteTime ? detailInfo.withdrawalCompleteTime : '--' }}
          </a-descriptions-item>
          <a-descriptions-item label="状态">
            {{ handleStatus(detailInfo.status) }}
          </a-descriptions-item>
        </a-descriptions>
      </a-card>
    </a-modal>
  </page-container>
</template>
